<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import PageContainer from '@/components/PageContainer.vue' // 导入组件不要大括号，要加.vue后缀
import { useUserStore } from '@/stores'
import { putMyUserInfoService } from '@/api/user'

const { userInfo, getUserInfo } = useUserStore()
const formRef = ref()

const formModel = ref({
  id: userInfo.id,
  username: userInfo.username, // 示例登录名，真实情况可从接口传入
  nickname: userInfo.nickname,
  email: userInfo.email
})

const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '昵称长度应为 2 到 10 位',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ]
}

const onSubmit = async () => {
  await formRef.value.validate()
  await putMyUserInfoService(formModel.value)
  getUserInfo()
  ElMessage.success('修改成功')
}
</script>

<template>
  <PageContainer title="基本资料">
    <el-form
      :model="formModel"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="formModel.username" disabled />
      </el-form-item>

      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formModel.nickname" />
      </el-form-item>

      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="formModel.email" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>
